// 股票组合指令
import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, message } from 'antd';
import { FormGroup, DATA_ENTRY, PrimaryC, UploadC, PrimaryGhostC, TableC, SecuritiesCodeC, InputC, InputNumberC, ModalC } from '../../../comps';
import Card from './card';
import stockGroupValues from '../../../utils/enumeratedValues/stockGroup';
import uuid from 'es6-uuid';
import _ from 'lodash';
import { exportFile } from '../../../utils/commonFunc';
import style from './index.less';
@Form.create()
class StockGroupDetail extends React.Component {
  state = {
    newClumns: [], // 表格行
    dataSource: [], // 表格数据
    stockNumber: 0, // 股票数量
    editDataSource: {}, // 编辑前数据
    isCalculate: false, // 导出前是否计算
    calculateData: {}, // 计算数据
    isEdit: false, // 是否处于编辑状态
    uploadShow: false, // 导入模态框是否打开
    cardData: {}, // 卡片数据
    isProduct: false, // 产品是否选择
    isAdd: false, // 是否处于新建
    gzCode: undefined, // 产品code
    page: {
      current: 1,
    },
  };

  //初始化函数
  componentDidMount() {
    const {
      stockGroupOrderM: { clumns },
    } = this.props;
    this.clumnsChange(clumns);
  }

  // 证券代码证券改变事件
  handleChange = (e, record) => {
    let { dispatch } = this.props;
    const { dataSource } = this.state;
    const arr = dataSource.filter((item) => item.id == record); //匹配数据
    const index = dataSource.findIndex((item) => item.id == record); //查找数据位置
    if (e) {
      dispatch({
        type: 'couponPoolApprovalM/getIndustryAndRole', //获取行业
        payload: {
          tradingCode: e.tradingCode,
          exchangeCode: e.exchangeCode,
        },
        callback: (res) => {
          if (res) {
            if (res.code == 0) {
              arr[0].industry = res.data?.dataSource?.industry;
              (arr[0].securityName = e.secuabbr), (arr[0].exchangeCode = e.exchangeCode), dataSource.splice(index, 1, arr[0]);
              this.setState({
                dataSource,
              });
            } else {
              arr[0].industry = '';
              (arr[0].securityName = e.secuabbr), (arr[0].exchangeCode = e.exchangeCode), dataSource.splice(index, 1, arr[0]);
              this.setState({
                dataSource,
              });
            }
          }
        },
      });
    } else {
      arr[0].industry = undefined;
      (arr[0].securityName = undefined), (arr[0].exchangeCode = undefined), dataSource.splice(index, 1, arr[0]);
      this.setState({
        dataSource,
      });
    }
  };

  // 新建点击响应
  addNew = () => {
    if (this.props.direction == 2) {
      if (!this.state.isProduct) {
        message.error('请先选择产品');
        return;
      }
    }
    let newDataSource = this.state.dataSource || [];
    newDataSource.unshift({
      id: uuid(32),
    });
    this.setState(
      {
        dataSource: [...newDataSource],
        stockNumber: this.state.stockNumber + 1,
        isAdd: true,
      },
      () => {
        this.forData(newDataSource[0].id, 5);
      },
    );
  };

  // 计算点击响应
  calculate = () => {
    const { dataSource, gzCode } = this.state;
    const { direction, dispatch } = this.props;
    let calculateData = this.getData.getFormGroupData(); //获取计算数据
    if (calculateData) {
      if (calculateData.allocateWay == undefined || calculateData.orderMoney == undefined || calculateData.priceModel == undefined) {
        message.error('请填写完整计算条件');
        return;
      }
    } else {
      message.error('请填写完整计算条件');
      return;
    }
    let resArr = [];
    for (let i of dataSource) {
      // 获取表格数据
      let newArr = {};
      newArr.securityCode = i.securityCode;
      newArr.weight = i.isEditWeight == 1 ? i.allocateWeight : null;
      newArr.exchangeCode = i.exchangeCode;
      newArr.isEditWeight = i.isEditWeight == 1 ? 1 : 0;
      resArr.push(newArr);
    }
    calculateData.item = resArr;
    calculateData.direction = direction;
    calculateData.product = gzCode;
    this.setState({ calculateData, isCalculate: true });
    dispatch({
      type: 'stockGroupOrderM/getTableData',
      payload: calculateData,
      callback: (res) => {
        if (res) {
          if (res.code == 0) {
            this.setState({
              dataSource: res.data.dataSource,
              cardData: res.data.cardData,
              stockNumber: res.data.cardData.stockNumber,
            });
          } else {
            this.setState({
              dataSource: [],
              cardData: {},
            });
          }
        }
      },
    });
  };

  // 表格行优化
  clumnsChange = (clumns) => {
    const { isEdit } = this.state;
    const { direction } = this.props;
    clumns.map((item) => {
      if (item.key == 'operate') {
        item.operates = [
          {
            title: '编辑',
            onClick: (record, index) => {
              this.editData(record.id);
            },
            rules: {
              // 禁用逻辑：证券为停牌或涨停，或某条数据处于编辑状态
              disabled: {
                items: [
                  { key: 'securityType', value: [0, 1, 2], relation: ['=', '=', '='] },
                  { key: 'isDisabled', value: [undefined], relation: ['!='] },
                ],
                relation: 'or',
              },
              // 隐藏逻辑：点击编辑时隐藏编辑和删除按钮，展示保存和取消按钮
              hide: { items: [{ key: 'edit', value: [undefined], relation: ['!='] }] },
            },
          },
          {
            title: '删除',
            onClick: (record, index) => {
              this.deleteData(record.id);
            },
            rules: {
              // 禁用逻辑：某条数据处于编辑状态
              disabled: {
                items: [{ key: 'isDisabled', value: [undefined], relation: ['!='] }],
                relation: 'or',
              },
              // 隐藏逻辑：点击编辑时隐藏编辑和删除按钮，展示保存和取消按钮
              hide: { items: [{ key: 'edit', value: [undefined], relation: ['!='] }] },
            },
          },
          {
            title: '保存',
            onClick: (record, index) => {
              this.saveData(record.id);
            },
            rules: {
              // 隐藏逻辑：点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
              hide: { items: [{ key: 'edit', value: [undefined], relation: ['='] }] },
            },
          },
          {
            title: '取消',
            onClick: (record, index) => {
              this.cancelData(record.id);
            },
            rules: {
              // 隐藏逻辑：点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
              hide: { items: [{ key: 'edit', value: [undefined], relation: ['='] }] },
            },
          },
        ];
      }

      if (item.key == 'securityCode') {
        item.render = (val, record) => {
          if (record.edit) {
            return (
              <SecuritiesCodeC
                form={this.props.form}
                initialValue={record?.exchangeCode && record?.securityCode ? record?.exchangeCode + '-' + record?.securityCode : ''}
                dataIndex={'securityCode'}
                onChange={(e) => this.handleChange(e, record?.id)}
                titleDisplay={false}
                codeType={direction == 2 ? 'inProduct' : 'stock'}
                queryItems={direction == 2 ? { gzCode: this.state.gzCode, exchangeCode: '101,105', valid: 1 } : { exchangeCode: '101,105', valid: 1 }}
                disabled={isEdit ? true : false}
                rules={[{ required: true, message: ' ' }]}
                positionBody={true}
              />
            );
          } else {
            return val;
          }
        };
      }
      if (item.key == 'allocateWeight') {
        item.render = (val, record) => {
          if (record.edit) {
            return (
              <InputNumberC
                form={this.props.form}
                dataIndex={'allocateWeight'}
                initialValue={val ? val * 100 : ''}
                unit={'%'}
                precision={2}
                min={0}
                disabled={isEdit ? false : true}
              />
            );
          } else {
            if (val == null || val === undefined || val === '') {
              return '--';
            } else {
              // NaN: Not a Number
              // isNaN()的缺点就在于 null、空格以及空串会被按照0来处理
              if (isNaN(val)) {
                return val;
              } else {
                return (Number(val) * 100).toFixed(2) + '%';
              }
            }
          }
        };
      }
    });

    this.setState({ newClumns: clumns });
  };

  //编辑点击响应
  editData = (id) => {
    this.setState(
      {
        isEdit: true, // 表格处于编辑状态
      },
      () => {
        this.forData(id, 1);
      },
    );
  };
  //删除点击响应
  deleteData = (id) => {
    this.forData(id, 2);
  };
  // 保存响应
  saveData = (id) => {
    this.forData(id, 3);
  };
  // 取消响应
  cancelData = (id) => {
    this.setState({ isEdit: false, isAdd: false });
    this.forData(id, 4);
  };
  // 匹配表格数据
  forData = (id, type) => {
    const { dataSource, editDataSource, isEdit, isAdd } = this.state;
    const {
      stockGroupOrderM: { clumns },
      form: { getFieldValue },
      direction,
    } = this.props;
    const arr = dataSource.filter((item) => item.id == id); //匹配数据
    const index = dataSource.findIndex((item) => item.id == id); //查找数据位置
    if (type == 1) {
      arr[0].isEditWeight = 1;
    }
    if (type == 1 || type == 5) {
      // 编辑前保存此条数据信息，以便用户取消操作赋值
      let editDataSource = _.cloneDeep(arr[0]);
      this.setState({
        editDataSource,
      });
      dataSource.map((item) => (item.isDisabled = true)); // 当有一条数据处于编辑状态时，其他数据不可编辑
      arr[0].edit = true;
      dataSource.splice(index, 1, arr[0]);
    } else if (type == 3) {
      //保存操作
      if (getFieldValue('securityCode')) {
        if (isAdd) {
          let isRepetition = dataSource.some((item) => item.securityCode == getFieldValue('securityCode')?.split('-')[1]);
          if (isRepetition) {
            message.error('证券代码已存在');
            return;
          }
        }
        arr[0].edit = undefined;
        arr[0].securityCode = getFieldValue('securityCode')?.split('-')[1];
        arr[0].allocateWeight = getFieldValue('allocateWeight') ? getFieldValue('allocateWeight') / 100 : getFieldValue('allocateWeight');
        dataSource.map((item) => (item.isDisabled = undefined));
      } else {
        message.info('请填写证券代码');
      }
      dataSource.splice(index, 1, arr[0]);
      // 点击保存时表示表格数据改变，需重新计算
      this.setState({ isCalculate: false, isEdit: false, isAdd: false });
    } else if (type == 4) {
      if (isEdit) {
        //取消操作，将数据还原到编辑之前的
        arr[0].isEditWeight = 0;
        arr[0].edit = undefined;
        arr[0].securityCode = editDataSource.securityCode;
        arr[0].securityName = editDataSource.securityName;
        arr[0].exchangeCode = editDataSource.exchangeCode;
        arr[0].industry = editDataSource.industry;
        arr[0].allocateWeight = editDataSource.allocateWeight;
        dataSource.map((item) => (item.isDisabled = undefined));
        dataSource.splice(index, 1, arr[0]);
      } else {
        dataSource.map((item) => (item.isDisabled = undefined));
        dataSource.splice(index, 1);
        this.setState({ stockNumber: this.state.stockNumber - 1, isCalculate: false });
      }
    } else {
      // 删除操作
      dataSource.splice(index, 1);
      this.setState({ stockNumber: this.state.stockNumber - 1, isCalculate: false });
    }

    this.setState({ dataSource }, () => this.clumnsChange(clumns));
  };

  // 导入
  upLoad = (file) => {
    if (this.props.direction == 2) {
      if (!this.state.isProduct) {
        message.error('请先选择产品');
        return;
      }
    }
    const formData = new FormData();
    formData.append('file', file);
    if (this.props.direction == 2) {
      formData.append('gzCode', this.state.gzCode);
    }
    this.props.dispatch({
      type: 'stockGroupOrderM/upLoad',
      payload: formData,
      callback: (data) => {
        if (data) {
          this.setState({
            uploadData: data,
            stockNumber: data.success,
            uploadShow: true,
          });
        }
      },
    });
  };
  //导入错误信息表格优化
  errorColumnsChange = (columns) => {
    if (columns) {
      columns.map((item) => {
        if (item.key != 'errormessage') {
          item.align = 'center';
        }
      });
    }
    return columns;
  };
  //导入模态框
  templateUpLoad = () => {
    const { uploadShow, uploadData } = this.state;
    let errorColumns = this.errorColumnsChange(uploadData?.errorColumns);
    const modalProps = {
      destroyOnClose: true,
      visible: uploadShow,
      maskClosable: true,
      title: '提示',
      width: 700,
      onCancel: () => {
        this.setState({
          uploadShow: false,
        });
      },
      onOk: () => {
        this.setState({
          uploadShow: false,
          dataSource: uploadData ? uploadData.dataSource : [],
          isCalculate: false,
        });
      },
    };

    return (
      <ModalC {...modalProps}>
        <div className={style.batchUploadOne}>
          共{uploadData?.total}条，其中，导入成功，{uploadData?.success}条；导入失败，{uploadData?.error}条。
        </div>
        <div className={style.batchUpload}>点击取消，重新导入；点击确定，导入成功的标的会自动填充到新建标的列表。</div>
        {uploadData?.error != '0' && <TableC columns={errorColumns} dataSource={uploadData?.errorDataSource} rowKey='id' hidePage={true} />}
      </ModalC>
    );
  };
  //导出
  export = () => {
    if (!this.state.isCalculate) {
      message.warning('计算数据变更，请重新计算后导出');
      return;
    }
    let exportData = _.cloneDeep(this.state.calculateData);
    exportData.item = JSON.stringify(this.state.dataSource);
    exportFile('gateway/portfolio-server/portfolioOrder/export', exportData);
  };

  // 模板下载
  downLoad = () => {
    exportFile('gateway/portfolio-server/portfolioOrder/download-template');
  };

  // 产品点击
  productOnChange = (e) => {
    if (e) {
      this.setState({
        isProduct: true,
        gzCode: e.info.portfolioCode,
      });
    } else {
      this.setState({
        isProduct: false,
        gzCode: undefined,
      });
    }
  };
  //表格分页
  // handleTableChange = (current, pageSize) => {
  //     this.setState({
  //         page: {
  //             current: current,
  //         }
  //     })
  // };
  render() {
    const { dataSource, stockNumber, newClumns, isEdit, cardData, isAdd, page } = this.state;
    const { loading } = this.props;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'product',
          title: '产品',
          type: DATA_ENTRY.PRODUCTLIST,
          onChange: this.productOnChange,
          disabled: isAdd || isEdit,
          exist: 1,
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE'], //不包含估值解析和估值对接的产品
        },
        {
          dataIndex: 'orderMoney',
          title: '下单金额',
          type: DATA_ENTRY.INPUTNUMBER,
          min: '0',
          splitStyle: true,
          precision: 2,
        },
        {
          dataIndex: 'priceModel',
          title: '价格模式',
          type: DATA_ENTRY.SELECT,
          dataSource: stockGroupValues.peiceModel,
        },
        {
          dataIndex: 'allocateWay',
          title: '分配方式',
          type: DATA_ENTRY.SELECT,
          dataSource: stockGroupValues.allocateWay,
          disabled: isEdit,
        },
      ],
    };
    return (
      <div style={{ marginTop: '10px' }}>
        {/* 计算条件 */}
        <FormGroup
          {...searchProps}
          onRef={(ref) => {
            this.getData = ref;
          }}
        />
        {/* 卡片信息 */}
        <div>
          <Card stockNumber={stockNumber} cardData={cardData} loading={loading.effects['stockGroupOrderM/getTableData']} />
        </div>
        {/* 新建、计算、导入导出按钮 */}
        <div style={{ marginTop: '16px', marginBottom: '16px' }}>
          <div style={{ display: 'flex' }}>
            <PrimaryC onClick={() => this.addNew()} title={'新建'} disabled={isEdit || isAdd} />
            <PrimaryC
              onClick={() => this.calculate()}
              title={'计算'}
              style={{ flex: 1, marginLeft: '16px' }}
              disabled={isEdit || isAdd}
              loading={this.props.loading.effects['stockGroupOrderM/getTableData'] === true}
            />
            <PrimaryGhostC title={'模板下载'} onClick={this.downLoad} style={{ marginRight: '16px' }} />
            <UploadC
              title='导入'
              accept='.xlsx,.xls'
              showUploadList={false}
              type={2}
              disabled={isEdit || isAdd}
              onUpload={(e) => {
                this.upLoad(e);
              }}
            />
            <PrimaryGhostC title={'导出'} disabled={isEdit || isAdd} onClick={this.export} style={{ marginLeft: '16px' }} />
          </div>
        </div>
        {/* 表格 */}
        <div>
          <TableC
            columns={newClumns}
            dataSource={dataSource}
            rowKey='id'
            scroll={{ x: 1800 }}
            selfScrollY={true}
            loading={loading.effects['stockGroupOrderM/getTableData']}
            hidePage={true}
            // current={page.current}
            // pageSizeOptions={['10']}
            // pageSize={10}
            // onPageChange={this.handleTableChange}
          />
        </div>
        {this.templateUpLoad()}
      </div>
    );
  }
}

export default connect(({ stockGroupOrderM, couponPoolApprovalM, loading }) => ({
  stockGroupOrderM,
  couponPoolApprovalM,
  loading,
}))(StockGroupDetail);
